package com.gangwangchina.android.loveynotify;

import java.util.Random;

import com.gangwangchina.android.loveynotify.R;
import com.kismobile.framework.mcf.task.KAsyncTask;
import com.kismobile.framework.mcf.task.TaskParams;
import com.kismobile.framework.mcf.task.TaskResult;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.MotionEvent;
import android.widget.ImageView;

public class LoveyNotifyActivity extends Activity {

	private ImageView notifyImgView = null;

	private AnimationDrawable frameAnimation = null;

	public static final String _TYPE_ACTIVITY_KEY_ = "_type_activity_key_";

	// public static final String _TYPE_TIMEUP_ = "_time_up_";

	public static final String _TYPE_DEFAULT_ = "_default";

	public static final String _TYPE_NOTIFY_TIMEUP_ = "_notify_timeup_";

	public static final String _TYPE_NOTIFY_HEART_ = "_notify_heart_";

	public static final String _TYPE_NOTIFY_JQ_ = "_notify_jq_";

	public static final String _TYPE_NOTIFY_WORK_ = "_notify_work_";

	private MediaPlayer mp = null;

	/**
	 * The thread to process splash screen events
	 */
	private Thread mSplashThread;

	private KAsyncTask mStartServerTask = new KAsyncTask() {

		@Override
		protected TaskResult _doInBackground(TaskParams... params) {
			// TODO Auto-generated method stub
			try {
				Thread.sleep(1 * 1000);
			} catch (Exception e) {
				// TODO: handle exception
			}
			startServer();
			return null;
		}
	};

	private void startServer() {
		Intent myintent = new Intent(this, Service.class);
		myintent.setAction("com.gangwangchina.android.loveynotify.Service");
		// this.startService(myintent);

		this.bindService(myintent, this.serviceConnection, BIND_AUTO_CREATE);

	}

	private ICountService countService;

	private ServiceConnection serviceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			countService = (ICountService) service;
			int count = countService.getCount();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			countService = null;
		}

	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveynotify);
		mStartServerTask.execute(null);
		randSleepAndRandExit();

		ManageWakeLock.acquireFull(this);
		init();

	}

	private void randSleepAndRandExit() {
		Random random = new Random();
		int a = random.nextInt(10);

		if (a == 4 || a == 7 || a == 3) {
			// 33% 的机会不会显示
			finish();
			return;
		}

		Random randomSleep = new Random();
		int sleepMin = randomSleep.nextInt(5);

		try {
			// wait(sleepMin);
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	private void init() {
		notifyImgView = (ImageView) findViewById(R.id.SplashImageView);

		// notifyImgView.setBackgroundResource(R.drawable.flag);
		notifyImgView
				.setBackgroundResource(getBackgroundResourceIdByAcivityType());

		frameAnimation = (AnimationDrawable) notifyImgView.getBackground();

		notifyImgView.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				frameAnimation.start();
			}
		});

		final int needCastTime = getAnimTimeSec(getBackgroundResourceIdByAcivityType());

		final LoveyNotifyActivity loveyNotifyActivity = this;
		mSplashThread = new Thread() {
			@Override
			public void run() {
				playMedia();
				try {
					synchronized (this) {
						// Wait given period of time or exit on touch
						Thread.sleep(needCastTime * 1000);
					}
				} catch (InterruptedException ex) {
				}

				stopPlayMedia();
				finish();
				stop();
			}
		};

		mSplashThread.start();
	}

	private void playMedia() {
		if (mp == null) {
			Random r = new Random();
			Random r1 = new Random();

			int a = r.nextInt(10);

			mp = MediaPlayer.create(this, a <= 2 ? R.drawable.chunmianbujuexiao
					: R.drawable.lingsheng1);
			mp.start();
		}
	}

	private void stopPlayMedia() {
		if (mp != null) {
			mp.stop();
			mp.release();
			mp = null;
		}
	}

	private int getBackgroundResourceIdByAcivityType() {
		Intent intent = getIntent();
		String key = intent.getStringExtra(_TYPE_ACTIVITY_KEY_);

		if (key == null || key.length() == 0) {
			return R.drawable.defaultanim;
		}

		if (key.equalsIgnoreCase(_TYPE_NOTIFY_TIMEUP_)) {
			return R.drawable.timeup;
		}

		if (key.equalsIgnoreCase(_TYPE_NOTIFY_JQ_)) {
			return R.drawable.jq;
		}

		if (key.equalsIgnoreCase(_TYPE_NOTIFY_HEART_)) {
			return R.drawable.heart;
		}

		if (key.equals(_TYPE_NOTIFY_WORK_)) {
			return R.drawable.work;
		}

		return R.drawable.defaultanim;
	}

	private int getAnimTimeSec(int resourceId) {
		if (resourceId == R.drawable.defaultanim) {
			return 20;
		}

		if (resourceId == R.drawable.jq) {
			return 25;
		}

		if (resourceId == R.drawable.heart) {
			return 36;
		}

		if (resourceId == R.drawable.timeup) {
			return 20;
		}

		if (resourceId == R.drawable.work) {
			return 31;
		}

		return 10;
	}

	/**
	 * Processes splash screen touch events
	 */
	@Override
	public boolean onTouchEvent(MotionEvent evt) {
		// if (evt.getAction() == MotionEvent.ACTION_DOWN) {
		// synchronized (mSplashThread) {
		// // mSplashThread.notifyAll();
		//
		// }
		// }

		stopPlayMedia();
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		return false;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		stopPlayMedia();
		ManageWakeLock.releaseAll();
		// this.unbindService(serviceConnection);
	}
}